require "Task"
require "TaskCategory/RandomTask"
require "WeightPool"

QNW_TS_PlayerOnTeleport = QNW_TS_Task:derive("QNW_TS_PlayerOnTeleport")

local this = QNW_TS_PlayerOnTeleport
this.name = getText("IGUI_QNW_TaskSystem_Task_PlayerOnTeleport_Name")
this.desc = getText("IGUI_QNW_TaskSystem_Task_PlayerOnTeleport_Desc")
this.taskCategory = QNW_TS_RandomTask

function QNW_TS_PlayerOnTeleport:isComplete()
    return self:isTime()
end

function QNW_TS_PlayerOnTeleport:complete()
    if QNW_TS_TaskWindow.instance then
        QNW_TS_TaskWindow.instance:destroy()
    end
    QNW_TS_Task.complete(self)
    local player = getPlayer()
    local warn = getText("IGUI_PlayerOnTeleport_Warn")
    PlayerOnTeleportlocal(player)
    processGeneralMessage(warn)
end

function QNW_TS_PlayerOnTeleport:isAbandon()
    return self:isTime()
end

function QNW_TS_PlayerOnTeleport:getProgress()
    return ""
end

function QNW_TS_PlayerOnTeleport:registerClient(_player)
    _player:Say(getText("IGUI_QNW_TaskSystem_Get", self.name))
end

function QNW_TS_PlayerOnTeleport:save()
    local save = {}
    save.Type = self.Type
    save.uuid = self.uuid
    save.time = self.time
    save.rewards = {}
    for k, v in pairs(self.rewards) do
        table.insert(save.rewards, v:save())
    end
    return save
end

function QNW_TS_PlayerOnTeleport:load(_table)
    self.uuid = _table.uuid
    self.time = _table.time
    if _table.rewards then
        self:loadReward(_table.rewards)
    end
end

function QNW_TS_PlayerOnTeleport:new()
    local o = QNW_TS_Task:new()
    setmetatable(o, self)
    self.__index = self

    o.uuid = getRandomUUID()
    o.time = getGameTime():getCalender():getTimeInMillis() + 60 * 60 * 6000

    return o
end

function QNW_TS_PlayerOnTeleport:initReward()
    QNW_TS_ClientCommand.randomReward(self, "premium", 2)
end


local rewardlist = {"Base.SuiPian", "Base.CreditCard", "Base.SuiPian"}
local rewardCountlist = {7, 4, 2}

function PlayerOnTeleportlocal(playerObj)
    local PlayerMember = getOnlinePlayers()
    for i = 0, PlayerMember:size() - 1 do
        local Targetplayer = PlayerMember:get(i)
        local PlayerSquareOnFoot = Targetplayer:getCurrentSquare()
        if not SafeHouse.isSafeHouse(PlayerSquareOnFoot, nil, true) then
            if Targetplayer == playerObj then
                print("youself")
                playerObj:Say(getText("IGUI_TPfailed"))
            else
                playerObj:setX(Targetplayer:getX())
                playerObj:setY(Targetplayer:getY())
                playerObj:setZ(Targetplayer:getZ())

                local num = ZombRand(1, 3)
                local Type = rewardlist[num]
                local Count = rewardCountlist[num]
                playerObj:getInventory():AddItems(Type, Count)

                return
            end
        end
        print("none")
    end
end
